package com.benchmark.springboot.component;

import com.power.common.util.OkHttp3Util;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * OkHttp异步客服端
 *
 * @author yu 2019/8/5.
 */
@Component
public class OkHttpAsyncClient {

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpAsyncClient.class);

    @Resource
    private OkHttpClient okHttpClient;

    /**
     * Asynchronous post json request with headers
     *
     * @param url        request url
     * @param json       json data
     * @param headersMap request headers
     * @param callback   call back
     */
    public void asyncPostJson(String url, String json, Map<String, String> headersMap, Callback callback) {
        RequestBody body = RequestBody.create(JSON_TYPE, json);
        LOGGER.debug("OkHttp3 async post json param:{} ", json);
        OkHttp3Util.asyncPost(this.okHttpClient, url, body, headersMap, callback);
    }


    /**
     * Asynchronous post json request
     *
     * @param url      request url
     * @param json     json data
     * @param callback call back
     */
    public void asyncPostJson(String url, String json, Callback callback) {
        this.asyncPostJson(url, json, null, callback);
    }

    /**
     * Simple async get request.
     *
     * @param url      request
     * @param callback call back
     */
    public void asyncGet(String url, Callback callback) {
        this.asyncGet(url, null, null, callback);
    }

    /**
     * Asynchronous get request with parameters
     *
     * @param baseUrl  request base url
     * @param params   request params
     * @param callback callback
     */
    public void asyncGet(String baseUrl, Map<String, String> params, Callback callback) {
        this.asyncGet(baseUrl, params, null, callback);
    }

    /**
     * Asynchronous get request with parameters and headers
     *
     * @param baseUrl  request base url
     * @param params   request params
     * @param headers  request headers
     * @param callback call back
     */
    public void asyncGet(String baseUrl, Map<String, String> params, Map<String, String> headers,
                         Callback callback) {
        OkHttp3Util.asyncGet(this.okHttpClient, baseUrl, params, headers, callback);
    }
}
